package com.hetang.maijiayun.adaptertools.commons.group;

import java.util.*;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public enum GroupObject {
	/**
	 * 实例
	 */
	INSTANCE;
	/**
	 * 日志
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(GroupObject.class);
	
	/**
	 * 
	 * @param colls
	 * @param gb
	 * @return
	 */
	public final <T extends Comparable<T>, D> Map<T, List<D>> group(Collection<D> colls, GroupInterface<T> gb) {
        if(CollectionUtils.isEmpty(colls)) {
        	LOGGER.error("分组集合不能为空!!!");
            return null ;
        }
        if(gb == null) {
        	LOGGER.error("分组依据不能为空!!!");
            return null ;
        }
        Iterator<D> iter = colls.iterator() ;
        Map<T ,List<D>> map = new TreeMap<T, List<D>>() ;
        while(iter.hasNext()) {
            D d = iter.next() ;
            T t = gb.groupby(d) ;
            if(map.containsKey(t)) {
                map.get(t).add(d) ;
            } else {
                List<D> list = new ArrayList<D>() ;
                list.add(d) ;
                map.put(t, list) ;
            }
        }
        return map ;
    }

}
